package com.mozz.finally_work.servlet.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mozz.finally_work.dao.BlogDao;
import com.mozz.finally_work.pojo.Blog;
import com.mozz.finally_work.utils.MybatisUtils;
import com.mozz.finally_work.utils.ParseMarkdown;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "QueryBlogsByTagIdServlet", value = "/QueryBlogsByTagIdServlet")
public class QueryBlogsByTagIdServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*获取参数*/
        String tagId = request.getParameter("tagId");
        /*查询数据*/
        SqlSession session = MybatisUtils.getSession();
        BlogDao dao = session.getMapper(BlogDao.class);
        List<Blog> blogs = null;
        if (tagId.equals("all")) {
            blogs = dao.queryAllBlog();
        }else{
            blogs = dao.queryBlogsByTagId(tagId);
        }
        session.close();
        for (Blog blog : blogs) {
            String parse = ParseMarkdown.parse(blog.getContent());
            blog.setContent(parse);
        }
        /*响应请求*/
        /*设置请求头*/
        response.setHeader("Content-Type", "application/json; charset=UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        String ret = mapper.writeValueAsString(blogs);
        response.getWriter().write(ret);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
